'use client'

import axios, {AxiosRequestConfig, AxiosResponse} from "axios";
import {message} from 'antd';
import {AmisResp} from "@/types/types.ts";
import {useNavigate} from "react-router-dom";

const config = {
  timeout: 3000
}
const instance = axios.create(config);


export default function useReq() {
  const navigate = useNavigate();

  // 添加请求拦截器
  instance.interceptors.request.use(function (config) {
    config.headers.respFormat = 'amis'
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.authorization = 'Bearer ' + token
    }
    return config;
  }, function (error) {
    return Promise.reject(error);
  });

  // 添加响应拦截器
  instance.interceptors.response.use(function (response: AxiosResponse<AmisResp<object>>) {
    const {data} = response;
    if (data.status === 1003) {
      // eslint-disable-next-line @typescript-eslint/no-floating-promises
      message.error(data.msg);
      navigate('/login')
    }
    if (data.status !== 0) {
      // eslint-disable-next-line @typescript-eslint/no-floating-promises
      message.error(data.msg);
      throw new Error(data.msg);
    }
    return response;
  }, function (error) {
    return Promise.reject(error);
  });

  async function request<D, T>(url: string, config: AxiosRequestConfig<D>): Promise<AmisResp<T>> {
    const resp = await instance<AmisResp<T>>(url, config);
    return resp.data
  }

  return {request}
}

